<?php

/**
 * Show  login(register) page
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
class SiteController extends Controller {

    public $layout = 'site';

    /**
     * Declares class-based actions.
     */
    public function actions() {

	return array(
	    // captcha action renders the CAPTCHA image displayed on the contact page
	    'captcha' => array(
		'class' => 'CCaptchaAction',
		'backColor' => 0xFFFFFF,
	    ),
	    'newsletter' => array(
		'class' => 'application.widgets.newsletter.ANewsletter'
	    ),
	    'oauth' => array(
		// the list of additional properties of this action is below
		'class' => 'ext.hoauth.HOAuthAction',
		// Yii alias for your user's model, or simply class name, when it already on yii's import path
		// default value of this property is: User
		'model' => 'User',
		// map model attributes to attributes of user's social profile
		// model attribute => profile attribute
		// the list of avaible attributes is below
		'attributes' => array(
		    'email' => 'email',
		    'first_name' => 'firstName',
		    'last_name' => 'lastName',
		    'gender' => 'genderShort',
		    'display_name' => 'displayName',
		    'avatar' => 'photoURL',
		    'status' => 1
		////All attibute
//		    [identifier] => 100002719030701
//    [webSiteURL] => 
//    [profileURL] => https://www.facebook.com/duonghoang.tuan.98
//    [photoURL] => https://graph.facebook.com/100002719030701/picture?width=150&height=150
//    [displayName] => Duong Hoang Tuan
//    [description] => 
//    [firstName] => Duong Hoang
//    [lastName] => Tuan
//    [gender] => male
//    [language] => 
//    [age] => 
//    [birthDay] => 2
//    [birthMonth] => 12
//    [birthYear] => 1990
//    [email] => hoangtuan438@gmail.com
//    [emailVerified] => hoangtuan438@gmail.com
//    [phone] => 
//    [address] => 
//    [country] => 
//    [region] => 
//    [city] => 
//    [zip] => 
		),
	    ),
	    //oauth admin
	    'oauthadmin' => array(
		'class' => 'ext.hoauth.HOAuthAdminAction',
	    )
	);
    }

    /**
     * render site page
     */
    public function actionIndex() {

	if (user()->isGuest) {
	    $model = new User();
	    $model->gender = User::GENDER_MALE;
	    $success = '';
	    if (isset($_POST['sign-up'])) {
		$model->attributes = $_POST['User'];
		if ($model->validate()) {
		    $activationKey = getRandomKey(20);
		    $model->activation_key = $activationKey;
		    if ($model->save()) {
			//send mail	to active account
			$receiptContent = array(
			    'name' => $model->username,
			    'activationKey' => $activationKey,
			    'emailReceive' => $model->email
			);
			EmailHelper::sendMailResgistration($receiptContent);
			$success = 1;
		    }
		}
		$model->username = '';
		$model->email = '';
		$model->password = '';
		$model->postcode = '';
	    }
	    $aUsers = User::model()->findAll(array(
		'condition' => 'type!="admin"',
		'order' => 'user_id DESC',
		'limit' => 6
	    ));

	    $this->render('index', array('model' => $model, 'success' => $success, 'aUsers' => $aUsers));
	} else {
	    $this->redirect(url('user/dashboard/'));
	}
    }

    /**
     * Displays the contact page
     * @author Tuong Tran <tuong.tran@outlook.com>
     * @return void
     */
    public function actionContact() {
	$model = new ContactForm;
	if (isset($_POST['send-message'])) {
	    if (isset($_POST['ContactForm'])) {
		$model->attributes = $_POST['ContactForm'];
		if ($model->validate()) {
		    //
		    //save model
		    $contactUs = new ContactUs;
		    $contactUs->attributes = $model->attributes;

		    if ($contactUs->save()) {
			//send the email to admin
			EmailHelper::sendContactRequest($model);

			Yii::app()->user->setFlash('contact', '<div class="alert alert-success">Thank you for contacting us. We will respond to you as soon as possible.</div>');
		    }

		    $this->refresh();
		}
	    }
	}
	$this->render('contact', array('model' => $model));
    }

    /**
     * render faq page
     */
    public function actionSignup() {


	$this->render('signup');
    }

    /**
     * render eventcalendar page
     */
    public function actionEventCalendar() {

	$this->render('eventcalendar');
    }

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError() {
	if ($error = Yii::app()->errorHandler->error) {
	    if (Yii::app()->request->isAjaxRequest)
		echo $error['message'];
	    else
		$this->render('error', $error);
	}
    }

    /**
     * render custom layout
     * @param type $alias
     */
    public function actionPage($id) {

	$aPage = Yii::app()->db->createCommand('SELECT * FROM {{pages}} WHERE page_id=' . $id)->queryRow();

	if (count($aPage) < 0)
	    throw new CHttpException(404, 'The requested page does not exist.');
	$this->render('page', array('aPage' => $aPage));
    }

    /**
     * Displays the login page
     */
    public function actionLogin() {
	$model = new LoginForm;

	// if it is ajax validation request
	if (isset($_POST['ajax']) && $_POST['ajax'] === 'login-form') {
	    echo CActiveForm::validate($model);
	    Yii::app()->end();
	}

	// collect user input data
	if (isset($_POST['LoginForm'])) {
	    $model->attributes = $_POST['LoginForm'];
	    // validate user input and redirect to the previous page if valid
	    if ($model->validate() && $model->login()) {
		$this->redirect(Yii::app()->user->returnUrl);
	    }
	}
	// display the login form
	$this->render('login', array('model' => $model));
    }

    /**
     * Logs out the current user and redirect to homepage.
     */
    public function actionLogout() {
	Yii::app()->user->logout();
	$this->redirect(Yii::app()->homeUrl);
    }

    /**
     * This is the action to Clear Cache
     * From backend when administrator wants to clear all site cache using ccache class.
     * He must call this acction to flush front end cache
     */
    public function actionCaching() {
	if (isset($_POST['key'])) {
	    if ($_POST['key'] == FRONTEND_CLEAR_CACHE_KEY) {
		app()->cache->flush();
		echo '1';
	    }if (isset($_POST['key'])) {
		app()->cache->delete($_POST['key']);
	    }
	} else {
	    if (isset($_POST['setting']) && isset($_POST['category'])) {
		settings()->deleteCache($_POST['category']);
	    }
	}
    }

    /**
     * Forgot pass
     */
    public function actionForgot_password() {

	$success = '';
	$error = '';
	if (isset($_POST['submit'])) {
	    if ($_POST['email']) {
//		if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
		$model = User();
		$newPass = getRandomKey(15);

		$model = User::model()->find("email='" . $_POST['email'] . "' or username='" . $_POST['email'] . "'");
		if ($model) {
		    $model->password = $newPass;
		    $model->save();
		    $success = 1;

		    $resceipt = array(
			'email' => $model->email,
			'username' => $model->username,
			'pass' => $newPass
		    );
		    EmailHelper::sendForgotPassword($resceipt);
		} else {
		    $error = 'Invalid Email/Username';
		}
	    } else {
		$error = "Please enter email/username here.";
	    }
	}
	$this->render('forgot_password', array('success' => $success, 'error' => $error));
    }

    /**
     * active user when they click active 
     */
    public function actionActiveKey($key) {
	if ($key) {
	    Yii::app()->db->createCommand('UPDATE {{users}} SET activation_key="", status=1 WHERE activation_key="' . $key . '"')->execute();
	    Yii::app()->session['activeSuccess'] = 1;
	    $this->redirect(SITE_NAME_URL);
	}
    }

    /**
     * For login by social network
     * 
     * @param type $aUser
     * @param type $bIsNew
     */
    public function hoauthAfterLogin($aUser, $bIsNew) {
	$aUser->username = getUserNameByEmail($aUser->email);
	$aUser->save();
	user()->setModel($aUser);
    }

}

